<?php
/**
 * Copyright (c) 2018,2345
 * 摘    要：Account model
 * 作    者：林幸亿
 * 修改日期：2018.05.08
 */

/*
 * 参考网址: https://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
 */

namespace App\Models;

use PDO;
use \Library\Session;


class Account extends \Core\Model
{
    private static $db;
    
    public function __construct()
    {
        self::$db = static::getMySqlDB();
    }

    /**
     * 功    能：Authenticate the user login
     *
     * @return boolean
     * 修改日期：2018-05-08
     */    
    public static function auth($email, $password)
    {
        
        $result = self::$db->find("SELECT id, username, password FROM members WHERE email='" . $email . "' LIMIT 1");
        //die(var_dump($result));
        if ($result) {
            $db_password = $result['password'];
            if (password_verify($password, $db_password)) {
                    // Password is correct
                    //session = Session::getInstance();
                    // Set to true if using https
                    //$session->start_session('_s', false);
                //die('test');
                //session_start();
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];
                    // XSS protection as we might print this value
                    $user_id = preg_replace("/[^0-9]+/", "", $result['id']);
                    $_SESSION['user_id'] = $user_id;
                    // XSS protection as we might print this value
                    $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $result['username']);
                    
                    $_SESSION['username'] = $username;
                    $_SESSION['login_string'] = hash('sha512', $db_password . $user_browser);
                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    $now = time();
                    //$mysqli->query("INSERT INTO login_attempts(user_id, time)
                    //                VALUES ('$user_id', '$now')");
                    return false;
                }
        }
        else
        {
            // No user exists.
            return false;
        }
        
    }
    
    /**
     * 功    能：Check if the user is logged in
     *
     * @return boolean
     * 修改日期：2018-05-08
     */
    public static function checkAuth()
    {
        // Check if all session variables are set 
        if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {

            $user_id = $_SESSION['user_id'];
            $login_string = $_SESSION['login_string'];
            $username = $_SESSION['username'];

            // Get the user-agent string of the user.
            $user_browser = $_SERVER['HTTP_USER_AGENT'];

            $result = self::$db->find("SELECT password FROM members WHERE id = $user_id LIMIT 1");
            if ($result) {
                $db_password = $result['password'];

                $login_check = hash('sha512', $db_password . $user_browser);

                if (hash_equals($login_check, $login_string) ){
                    // Logged In!
                    return true;
                } else {
                    // Not logged in 
                    return false;
                }
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Not logged in 
            return false;
        }
    }
    
    /**
     * 功    能：Get a user
     * 修改日期：2018-5-4
     */
    public static function getOne($id)
    {
        return self::$db->find('SELECT id, name, email, mobile FROM contacts WHERE id=' . $id);
    }
    
    /**
     * 功    能：Get a user
     * 修改日期：2018-5-4
     */
    public static function insert($data=array())
    {
        $sql = "INSERT INTO contacts (name,email,mobile) values('" . $data['name'] . "','" . $data['email'] . "','" . $data['mobile'] . "')";
        $insertId= self::$db->insert($sql); //Return false if unsuccessful, else return insert Id
        return $insertId;
    }
    
    /**
     * 功    能：Get a user
     * 修改日期：2018-5-4
     */
    public static function update($id, $data=array())
    {
        $sql = "UPDATE contacts2 SET name = '" . $data['name'] . "', email = '" . $data['email'] . "', mobile ='" . $data['mobile'] . "' WHERE id = " . $id;
        $count = self::$db->update($sql); //Return -1 if unsuccessful
        //die(var_dump($count));
        return $count;
    }

    /**
     * 功    能：Get a user
     * 修改日期：2018-5-4
     */
    public static function delete($id)
    {
        $sql = "DELETE FROM contacts WHERE id = " . $id;
        $count = self::$db->delete($sql); //Return -1 if unsuccessful
        //die(var_dump($count));
        return $count;
    }
}
